package com.lantosec.hmrp.modules.archives.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lantosec.hmrp.core.config.InitDataListener;
import com.lantosec.hmrp.core.kit.PageVO;
import com.lantosec.hmrp.core.shiro.TokenUtil;
import com.lantosec.hmrp.core.util.DateUtils;
import com.lantosec.hmrp.core.util.UUIDUtils;
import com.lantosec.hmrp.modules.archives.entity.UserInfo;
import com.lantosec.hmrp.modules.archives.entity.UserWork;
import com.lantosec.hmrp.modules.archives.mapper.UserInfoMapper;
import com.lantosec.hmrp.modules.archives.service.IUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.modules.archives.service.IUserWorkService;
import com.lantosec.hmrp.modules.archives.vo.UserInfoVO;
import com.lantosec.hmrp.modules.system.entity.SysUser;
import com.lantosec.hmrp.modules.system.service.ISysDictionariesService;
import com.lantosec.hmrp.modules.uploads.entity.SysUploads;
import com.lantosec.hmrp.modules.uploads.service.ISysUploadsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Primary;
import lombok.extern.log4j.Log4j2;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-06-09
 */
@Service
@Primary
@Log4j2
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Autowired
    private ISysDictionariesService iSysDictionariesService;

    @Autowired
    private ISysUploadsService iSysUploadsService;

    @Autowired
    private IUserWorkService iUserWorkService;

    @Override
    public UserInfoVO getUserInfo(String userId) {
        UserInfoVO userInfoVO = new UserInfoVO();
        List<UserInfo> userInfoList = this.list(new QueryWrapper<UserInfo>().eq(UserInfo.ColName.user_id.toString(),userId)
                                                                            .in(UserInfo.ColName.verify_status.toString(),1,2));
        if(null != userInfoList && userInfoList.size() > 0){
            UserInfo userInfo = userInfoList.get(0);
            userInfoVO = getUserInfo(userInfo);
        }
        return userInfoVO;
    }

    @Override
    public List<UserInfoVO> getIntegrityList(String name) {
        List<UserInfoVO> userInfoVOList = new ArrayList<>();
        List<UserInfo> userInfoList = this.list(new QueryWrapper<UserInfo>().like(null != name,UserInfo.ColName.name.toString(),name)
                                                                            .eq(UserInfo.ColName.integrity_flag.toString(),1));
        userInfoList.forEach(param->{
            UserInfoVO userInfoVO = getUserInfo(param);
            String userId = param.getUserId();
            try {
                UserWork userWork = iUserWorkService.getOne(new QueryWrapper<UserWork>().eq(UserWork.ColName.user_id.toString(),userId)
                                                                                        .in(UserWork.ColName.verify_status.toString(),1,2));
                if(null != userWork){
                    userInfoVO.setWorkUnit(userWork.getWorkUnit());
                    userInfoVO.setMajorDuty(userWork.getMajorDuty());
                    userInfoVO.setDuty(userWork.getDuty());
                }
                userInfoVOList.add(userInfoVO);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return userInfoVOList;
    }

    @Override
    public String saveUserIntegrity(UserInfoVO vo) {
        //新增用户基本信息
        String userId = vo.getUserId();
        List<UserInfo> userInfoList = this.list(new QueryWrapper<UserInfo>().eq(UserInfo.ColName.user_id.toString(),userId)
                                                                            .in(UserInfo.ColName.verify_status.toString(),1,2));
        List<UserInfo> userInfoIntegrity = this.list(new QueryWrapper<UserInfo>().eq(UserInfo.ColName.user_id.toString(),userId).eq(UserInfo.ColName.integrity_flag.toString(),1));
        //判断该 用户是否已经设置为廉政
        if(userInfoIntegrity.size() > 0){
            return "该用户已建立廉政档案";
        }else {
            if(null != userInfoList && userInfoList.size() > 0){
                UserInfo userInfo = userInfoList.get(0);
                userInfo.setIntegrityFlag(1);
                this.updateById(userInfo);
                return "新增成功";
            }else {
                return "系统不存在该用户的信息";
            }
        }
    }

    @Override
    public PageVO<Map<String, Object>> getUserRewardsPunish(PageVO<Map<String, Object>> page,String userId) {
        return baseMapper.getUserRewardsPunish(page,userId);
    }

    @Override
    public PageVO<Map<String, Object>> getUserAppraisalRecord(PageVO<Map<String, Object>> page, String userId) {
        return baseMapper.getUserAppraisalRecord(page,userId);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserInfo(UserInfoVO vo) {
        //新增用户基本信息
        UserInfo userInfo = vo.convertToEntity();
        userInfo.setUserInfoId(UUIDUtils.get());
        userInfo.setUserId(UUIDUtils.get());
        //获取当前用户id和名称
        userInfo.setCreateId(TokenUtil.getUserId());
        userInfo.setCreateUser(TokenUtil.getName());
        userInfo.setCreateTime(DateUtils.nowDate());
        userInfo.setIntegrityFlag(0);
        userInfo.setVerifyStatus(0);
        this.save(userInfo);
        //新增用户
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userInfo.getUserId());
        sysUser.setUsername(userInfo.getEmployeeId());
        sysUser.setName(userInfo.getName());
        sysUser.setPhone(userInfo.getPhone());
        baseMapper.saveSysUser(sysUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfo(UserInfoVO vo) {
        UserInfo userInfo = vo.convertToEntity();
        String userInfoIdId = userInfo.getUserInfoId();
        userInfo.setUserInfoId(UUIDUtils.get());
        //获取当前用户id和名称
        userInfo.setCreateId(TokenUtil.getUserId());
        userInfo.setCreateUser(TokenUtil.getName());
        userInfo.setCreateTime(DateUtils.nowDate());
        userInfo.setVerifyStatus(0);
        userInfo.setIntegrityFlag(0);
        this.save(userInfo);
        //修改用户基本信息审核状态为2审核中
        UserInfo userInfo1 = new UserInfo();
        userInfo1.setUserInfoId(userInfoIdId);
        userInfo1.setVerifyStatus(2);
        this.updateById(userInfo1);
    }

    @Override
    public PageVO<UserInfoVO> getAll(PageVO<UserInfo> page,String name) {
        PageVO<UserInfoVO> userInfoVOPage = new PageVO<>();
        List<UserInfoVO> userInfoVOList = new ArrayList<>();
        //查询用户基本信息（审核状态为1和2的）
        PageVO<UserInfo> userInfoPage = this.page(page,new QueryWrapper<UserInfo>().like(null != name,UserInfo.ColName.name.toString(),name).in(UserInfo.ColName.verify_status.toString(),1,2));
        List<UserInfo> userInfoList = userInfoPage.getRecords();
        userInfoList.forEach(param->{
            UserInfoVO userInfoVO = getUserInfo(param);
            userInfoVOList.add(userInfoVO);
        });
        userInfoVOPage.setRecords(userInfoVOList);
        userInfoVOPage.setTotal(userInfoPage.getTotal());
        userInfoVOPage.setPageNo(userInfoPage.getPageNo());
        userInfoVOPage.setPageSize(userInfoPage.getPageSize());
        return userInfoVOPage;
    }

    @Override
    public List<UserInfoVO> getUserInfoVerify() {
        List<UserInfoVO> userInfoVOList = new ArrayList<>();
        //查询用户基本信息为未审核和审核中的
        List<UserInfo> userInfoList = this.list(new QueryWrapper<UserInfo>().in(UserInfo.ColName.verify_status.toString(),0,2));
        userInfoList.forEach(param->{
            UserInfoVO userInfoVO = getUserInfo(param);
            userInfoVOList.add(userInfoVO);
        });
        return userInfoVOList;
    }

    @Override
    public List<UserInfoVO> getUserInfoHistory(String userId) {
        List<UserInfoVO> userInfoVOList = new ArrayList<>();
        //查询用户基本信息为4历史记录的
        List<UserInfo> userInfoList = this.list(new QueryWrapper<UserInfo>().eq(UserInfo.ColName.user_id.toString(),userId).eq(UserInfo.ColName.verify_status.toString(),4)
                                                                            .orderByDesc(UserInfo.ColName.create_time.toString()));
        userInfoList.forEach(param->{
            UserInfoVO userInfoVO = getUserInfo(param);
            userInfoVOList.add(userInfoVO);
        });
        return userInfoVOList;
    }

    @Override
    public void verifyUserInfo(UserInfoVO vo) {
        UserInfo userInfo = vo.convertToEntity();
        Integer verifyStatus = userInfo.getVerifyStatus();
        //如果审核不通过
        if(vo.getState() == 0){
            //审核状态为审核中的变成 已审核
            if(verifyStatus == 2){
                userInfo.setVerifyStatus(1);
            }
            //审核状态为未审核的变成 审核不通过
            if(verifyStatus == 0){
                userInfo.setVerifyStatus(3);
            }
        }
        //如果审核通过
        if(vo.getState() == 1){
            //审核状态为审核中的变为 历史记录
            if(verifyStatus == 2){
                userInfo.setVerifyStatus(4);
            }
            //审核状态为未审核的变为 已审核
            if(verifyStatus == 0){
                userInfo.setVerifyStatus(1);
            }
        }
        //获取当前用户id和名称
        userInfo.setVerifyId(TokenUtil.getUserId());
        userInfo.setVerifyUser(TokenUtil.getName());
        userInfo.setVerifyTime(DateUtils.nowDate());
        this.updateById(userInfo);
    }

    /**
     * 查询用户基本信息
     * @param userInfo
     * @return
     */
    private UserInfoVO getUserInfo(UserInfo userInfo) {
        UserInfoVO userInfoVO = userInfo.convertToVO();
        try {
            //隐藏身份证
            String idCard = userInfo.getIdCard();
            if(StringUtils.isNotEmpty(idCard)){
                idCard = idCard.replaceAll("(\\d{4})\\d{10}(\\w{4})","$1*****$2");
                userInfoVO.setIdCard(idCard);
            }
            //查询字典表对应的性别
            String sex = userInfo.getSex();
            if(StringUtils.isNotEmpty(sex)){
                String sexName = iSysDictionariesService.getById(sex).getDictionariesShowName();
                userInfoVO.setSexName(sexName);
            }
            //查询字典表对应的民族
            String nation = userInfo.getNation();
            if(StringUtils.isNotEmpty(nation)){
                String nationName = iSysDictionariesService.getById(nation).getDictionariesShowName();
                userInfoVO.setNationName(nationName);
            }
            //查询字典表对应的籍贯
            String nativePlace = userInfo.getNativePlace();
            if(StringUtils.isNotEmpty(nativePlace)){
                String nativePlaceName = iSysDictionariesService.getById(nativePlace).getDictionariesShowName();
                userInfoVO.setNativePlaceName(nativePlaceName);
            }
            //查询字典表对应的政治面貌
            String politicalStatus = userInfo.getPoliticalStatus();
            if(StringUtils.isNotEmpty(politicalStatus)){
                String politicalStatusName = iSysDictionariesService.getById(politicalStatus).getDictionariesShowName();
                userInfoVO.setPoliticalStatusName(politicalStatusName);
            }
            //返回身份证图片(正)路径
            String idCardFront = userInfo.getIdCardFront();
            SysUploads sysUploads = new SysUploads();
            if(StringUtils.isNotEmpty(idCardFront)){
                sysUploads = iSysUploadsService.getById(idCardFront);
                userInfoVO.setSavePathFront(InitDataListener.uploadsUrl + sysUploads.getSavePath() + sysUploads.getFileName());
            }
            //返回身份证图片(反)路径
            String idCardBack = userInfo.getIdCardBack();
            if(StringUtils.isNotEmpty(idCardBack)){
                sysUploads = iSysUploadsService.getById(idCardBack);
                userInfoVO.setSavePathBack(InitDataListener.uploadsUrl + sysUploads.getSavePath() + sysUploads.getFileName());
            }
            //查询字典表对应的人事状态
            String personStatus = userInfo.getPersonStatus();
            if(StringUtils.isNotEmpty(personStatus)){
                String personStatusName = iSysDictionariesService.getById(personStatus).getDictionariesShowName();
                userInfoVO.setPersonStatusName(personStatusName);
            }
            //查询字典表对应的婚姻状态
            String marryStatus = userInfo.getMarryStatus();
            if(StringUtils.isNotEmpty(marryStatus)){
                String marryStatusName = iSysDictionariesService.getById(marryStatus).getDictionariesShowName();
                userInfoVO.setMarryStatusName(marryStatusName);
            }
            //返回个人照片路径
            String photo = userInfo.getPhoto();
            if(StringUtils.isNotEmpty(photo)){
                sysUploads = iSysUploadsService.getById(photo);
                userInfoVO.setPhotoSavePath(InitDataListener.uploadsUrl + sysUploads.getSavePath() + sysUploads.getFileName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userInfoVO;
    }
}
